﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using WorldOfMUDra;

namespace ServerEngine
{
    public partial class Server
    {
        static Socket _sck;
        public string Buffer;
        public const string Version = "0.0.2";
        public List<ServerClient> Clients;

        readonly int _port;

        public Server(int port, int maxClients)
        {
            _port = port;
            MaxClients = maxClients;
        }

        public Server(int port)
        {
            _port = port;
        }

        public int MaxClients { get; private set; }

        public void RemoveClient(ServerClient victim)
        {
            Clients.Remove(victim);
        }

        public void WorldWorldMessage(string msg)
        {
            foreach (Player p in Clients)
            {
                p.SendWorldMessage(msg);
            }
        }

        public void WorldChatMessage(string user, string msg)
        {
            foreach (Player p in Clients)
            {
                p.SendChatMessage(user, msg);
            }
        }

        public void WorldChatMessage(string msg)
        {
            WorldChatMessage("Server", msg);
        }

        public void Start()
        {

            _sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _sck.Bind(new IPEndPoint(0, _port));
            _sck.Listen(100);

            Clients = new List<ServerClient>();
            //WorldOfMUDra.Globals.PassFile = new WorldOfMUDra.PasswordStorageFile("userpasses.txt");
            CreateWorld();

            while (true)
            {
                try
                {
                    Console.WriteLine("Waiting for clients...");
                    Clients.Add(new Player(this, _sck.Accept()));
                    Console.WriteLine("Connection to " + Clients[Clients.Count - 1].IpAddress + " made. Now starting client thread...");
                    Clients[Clients.Count - 1].Run();
                    Console.WriteLine("Client thread started.");
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}
